var http = require("http");
var express = require("express");
var https = require("https")
var fs = require("fs");
var serverIndex = require("serve-index");
var app = express();
app.use(serverIndex('./public'));
app.use(express.static('./public'));
//引入Socket.io依赖
var socketIo = require("socket.io");
//引入Log4j
var log4js = require("log4js");
//配置log4j
log4js.configure({
	appenders:{
		file:{
			type:'file',
			filename:'app.log',
			layout:{
				type:'pattern',
				pattern:'%r %p - %m',
			}
		}
	},
	categories:{
		default:{
			appenders:['file'],
			level:'debug'
		}
	}
});
//获取logger
var logger = log4js.getLogger();
//配置证书
var options = {
	key : fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'),
	cert: fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem')
}
//配置https_server
var https_server = https.createServer(options,app);
//配置http_server
var http_server = http.createServer(app);
http_server.listen(8081,'0.0.0.0');
//绑定http_server
var io = socketIo.listen(https_server);
//处理链接
io.sockets.on('connection',(socket)=>{
	logger.info("INFOS:CONNECTION  SOCKET-"+socket.id);

	//发送信息
	socket.on('message',(room,data)=>{
		logger.info("INFOS:MESSAGE ROOM-"+room+"  DATA-"+data);
		socket.to(room).emit('messages',room,data,socket.id);
	});
	
	//用户进入房间提供join参数
	socket.on('join',(room)=>{
		logger.info("INFOS:JOIN ROOM-"+room);
		socket.join(room);
		//站点io查找房间
		var myRoom = io.sockets.adapter.rooms[room];
		//获取房间所有用户数量
		var users = Object.keys(myRoom.sockets).length;
		//输出日志
		logger.info('the number of user in room is: '+users);
		//在这里可以控制进入房间的人数
		if(users < 3 ){
			logger.info("INFOS:EMIT-JOINED ROOM-"+room+"  ID-"+socket.id);
			socket.emit('joined',room,socket.id);
		}else{
			logger.info("INFOS:LEAVE ROOM-"+room);
			socket.leave(room);
			logger.info("INFO:EMIT-FULL ROOM-"+room+"  ID-"+socket.id);
			socket.emit('full',room,socket.id);
		}
		//给本次链接发送消息
		//socket.emit('joined',room,socket.id);
		//除本链接外给某个房间所有人发送消息
		//socket.to(room).emit("joined",room,socket.id);
		//给某个房间所有人发送消息不包括自己
		//io.in(room).emit('joined',room,socket.id);
		//除本链接外 给所有人发送消息
		//socket.broadcast.emit("joined",room.socket.id);
	});
	//用户退出房间提供leave参数
	socket.on('leave',(room)=>{
		logger.info("INFOS:LEAVE ROOM-"+room);
		var myRoom = io.sockets.adapter.rooms[room];
		var users = Object.keys(myRoom.sockets).length;
		//打印日志
		logger.info("the number of user in room is :  "+users-1);
		socket.leave(room);
		logger.info("INFO:EMIT-BYE ROOM-"+room+"  ID-"+socket.id);
		socket.to(room).emit('bye',room,socket.id);
		logger.info("INFOS:EMIT-LEAVED ROOM-"+room+"  ID-"+socket.id);
		socket.emit('leaved',room,socket.id);
	});
});
//开启服务
https_server.listen(8080,"0.0.0.0");
